#!/usr/bin/python
# -*- coding: utf-8 -*-

import gtk, gobject, os
import cookielib
from thread2 import Thread
import urllib, urllib2, time
import HTMLParser
import gettext, locale
h = HTMLParser.HTMLParser()

def initLang():
	# internationalization suppport
	GETTEXT_DOMAIN = 'Trilulilu'
	LOCALE_PATH = os.path.join(os.path.dirname(os.path.abspath( __file__ )), 'i18n')
	locale.setlocale(locale.LC_ALL, '')
	for module in gtk.glade, gettext:
		module.bindtextdomain(GETTEXT_DOMAIN, LOCALE_PATH)
		module.textdomain(GETTEXT_DOMAIN)

class Main:
	def __init__(self):
		initLang();
		self.pluginName = 'Trilulilu'
		self.author = 'Ovidiu D. Niţan'
		self.version = '0.31'
		self.descriere = _('Plugin for downloading media files from Trilulilu.')
		self.updatecheck = 'http://redoxwap.freehostia.com/pymaxe_update.php?action=plugin_version&plugin=Trilulilu'
		if os.environ.get("APPDATA"):
			self.cookiefile = os.environ.get("APPDATA") + '\\pymaxe\\cookies';
		else:
			self.cookiefile = os.getenv("HOME") + '/.pymaxe/cookies';
			
		self.cj = cookielib.LWPCookieJar()
		if os.path.isfile(self.cookiefile):
			self.cj.load(self.cookiefile)
		self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cj))
		Thread(target=self.logIn).start()

	def start(self, pymaxe):
		try:
			pymaxe.triluliluMenu
		except:
			pymaxe.triluliluMenu = gtk.RadioMenuItem(pymaxe.gui.get_object('radiomenuitem1'), 'Trilulilu')
			pymaxe.triluliluMenu.show()
			pymaxe.gui.get_object('menu2').prepend(pymaxe.triluliluMenu)
			pymaxe.sites[self.pluginName] = 'trilulilu.ro'
		if pymaxe.getSetting('Plugins', 'TriluliluMusic') == None:
			pymaxe.setSetting('Plugins', 'TriluliluMusic', 'True')
		if pymaxe.getSetting('Plugins', 'TriluliluVideo') == None:
			pymaxe.setSetting('Plugins', 'TriluliluVideo', 'False')
		if pymaxe.getSetting('Plugins', 'TriluliluImage') == None:
			pymaxe.setSetting('Plugins', 'TriluliluImage', 'False')
		try:
			self.stopSearchConn = pymaxe.gui.get_object('button19').connect('clicked', self.stopSearch, pymaxe)
		except Exception, e:
			print e
			
	def logIn(self):
		from random import choice
		logins = ["action=login&username=c339243&remember=1&PAS5WORD=ff0f474ff5a229de1ac424315bf338b5&PAS5W0RD=800d183fbf0c3fc5153ac02912c58aaf&PA55WORD=cc586df972eae4f4bc21a1d0c4f70226&PASSW0RD=dddf9b5814da84a6d78e05fed5b3db85&PA5SW0RD=f5a3bcc5804ee91446846beebaf15c7b&PA5SWORD=d084fee6c5ebd5a1be5087910cb43b78&PA55W0RD=098322c5417ca3238ba90ce633369b8a&PASSWORD=6b00c059675e79bebb59246a931e9121",
"action=login&username=roxanapmaria&remember=1&PAS5WORD=0afbb7683f7573597de7740320f8bf49&PAS5W0RD=451bb36823d6607dbd73c12daab548b8&PA55WORD=51c1b643e7872cb6aee61549062ea06b&PASSW0RD=09e804e18c8e5832616dda378675c08e&PA5SW0RD=aee844c04bf2127ced891ab23c6d41e0&PA5SWORD=82ee4e0c3b6f46b6980bfcf098ff1fd1&PA55W0RD=87fe1637dd841933295ca8a50b5ef014&PASSWORD=f2e4a3c95ad05c441a212f54698aadf8", "action=login&username=pymaxe&remember=1&PAS5WORD=aa8fbdc261a77e10d19ca1c7a9654e1f&PAS5W0RD=760ad30b97b5c36a41a97c83121bf1f0&PA55WORD=d1423d9a2811b316c7d4eaa689a45309&PASSW0RD=d46cdf1f98e876ac5d91d22512944042&PA5SW0RD=3d6710ae417f74f1067239efb778924d&PA5SWORD=7a53ba3f403bafb100894f288449387f&PA55W0RD=cf61821dc7ee01dc0c2d8748e0fc1d63&PASSWORD=5a1a201663073d41cade390ee24fbd33", "action=login&username=selenush&remember=1&PAS5WORD=9d965598a05849d681f4d38a58b4d5e3&PAS5W0RD=c993bbce351ac6823d600367e570f816&PA55WORD=9766a8db9c733d11184a55fb2edf85da&PASSW0RD=c5eeca1e87720ae169d0e2cc88972fe5&PA5SW0RD=c5e0834e54d21f0e8536538d099ad3bb&PA5SWORD=9667f2ea9a4fa8e3170553782b9969ce&PA55W0RD=229e982fe463f90743cb2cdf601907d4&PASSWORD=cc35a9a8249c6a3ca99584d9f266d848",
"action=login&username=emamtza&remember=1&PAS5WORD=ebba7a56ec80c70526f824568f65a25b&PAS5W0RD=3a374edfa9feb1640951009583b18cd4&PA55WORD=b9d5601807ee106aca36233063db75aa&PASSW0RD=5116672a94c1ae56612a6b430809ddb2&PA5SW0RD=6dc9030766011db98a8c2a6d85972269&PA5SWORD=020f07b0e241f8b21c5dfd10642069f4&PA55W0RD=e9a99d1dd08b182864d14e0e81048596&PASSWORD=2a95f0a9cf0165a808231cd69b6d4d31",
"action=login&username=gagatelephone&remember=1&PAS5WORD=ac90a817b847131577a51e2673a01582&PAS5W0RD=f43fac80b0b54e79b33eca2ad8e52142&PA55WORD=fd99b34ed9a5e7cbb12cd8b2043c3169&PASSW0RD=bb834447943e7e91ef44a42e97f84ee8&PA5SW0RD=dea2962f1812bffe3a8d0c95beb26e2f&PA5SWORD=99cb6fd512e701e8e43834a6ebbe5e29&PA55W0RD=25d8036b1da5c9bb1e31a6f350100839&PASSWORD=29e0d76b125fa4772f9c1c3e9c5e5811",
"action=login&username=tempofred&remember=1&PAS5WORD=b531e0ddd3a7ab8f509f4c3ae3c61728&PAS5W0RD=ac63e50f3baa43c134715b5724912bb2&PA55WORD=75e2706e018babb73c613aa1f443a2dd&PASSW0RD=af043c613c969822b429d07333214930&PA5SW0RD=12f0646f52beeacb53ce9a12d6bc4923&PA5SWORD=a0edb477f54ab96e0b3cb46ce075a6e8&PA55W0RD=bf546576e8c9111826475f2d292c63ee&PASSWORD=6d2a95eb51e3fbdcf3e4d60465ab0d9e"]
		postdata = choice(logins)
		headers =  {'User-agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'}
		req = urllib2.Request("http://login.trilulilu.ro/", postdata, headers)
		getdata = self.opener.open(req);
		data = getdata.read();

		if data != 'ok'	:
			time.sleep(1)
			self.lRetries = self.lRetries + 1
			Thread(target=self.logIn).start()
	
	def search(self, pymaxe, string):
		print "[plugin] Trilulilu: searching for " + string
		self.tmusic = Thread(target=self.searchAudio, args=(string, pymaxe))
		self.tvideo = Thread(target=self.searchVideo, args=(string, pymaxe))
		self.timage = Thread(target=self.searchImage, args=(string, pymaxe))
		if pymaxe.getSetting('Plugins', 'TriluliluMusic') == 'True':
			self.tmusic.start()
		if pymaxe.getSetting('Plugins', 'TriluliluVideo') == 'True':
			self.tvideo.start()
		if pymaxe.getSetting('Plugins', 'TriluliluImage') == 'True':
			self.timage.start()

		while True:
			if self.tmusic.is_alive() == False and self.timage.is_alive() == False and self.tvideo.is_alive() == False:
				break;
			#pymaxe.isWorking = True
			time.sleep(1)

	def searchAudio(self, string, pymaxe):
		audio = gtk.gdk.pixbuf_new_from_file(__path__[0] + '/trilulilu_audio.png')
		req = urllib2.Request('http://cauta.trilulilu.ro/muzica/' + urllib.quote(string));
		getdata = self.opener.open(req);
		data = getdata.read();
		results = data.split('<div class="audio_item"');
		results.pop(0)
		for x in results:
			try:
				import time
				gurl = x.split('<span class="title"><a href="')
				gurl = gurl[1].split('">')
				url = gurl[0]
				gtitle = gurl[1].split('</a></span>')
				gtitle = gtitle[0]
				title = gtitle.replace('&#039;', "'")
				if '&amp;amp;' in title:
					title = title.replace('&amp;', '&')
				title = title.replace('&amp;', '&')
				title = '<b>' + gobject.markup_escape_text(title) + '</b>'
				gtime = x.split('<span class="duration">')
				gtime = gtime[1].split('</span>');
				timp = gtime[0]
				if len(timp) == 4:
					timp = '0' + timp
				gobject.idle_add(pymaxe.addToList, [audio, title, timp, url])
			except Exception, e:
				pass

	def searchVideo(self, string, pymaxe):
		video = gtk.gdk.pixbuf_new_from_file(__path__[0] + '/trilulilu_video.png')
		req = urllib2.Request('http://cauta.trilulilu.ro/video/' + urllib.quote(string));
		getdata = self.opener.open(req);
		data = getdata.read();
		results = data.split('<div class="item_list" playlist_class="video" ');
		results.pop(0)
		for x in results:
			try:
				import time
				gurl = x.split('<span class="title"><a href="')
				gurl = gurl[1].split('">')
				url = gurl[0]
				gtitle = gurl[1].split('</a></span>')
				gtitle = gtitle[0]
				title = gtitle.replace('&#039;', "'")
				if '&amp;amp;' in title:
					title = title.replace('&amp;', '&')
				title = title.replace('&amp;', '&')
				title = '<b>' + gobject.markup_escape_text(title) + '</b>'
				gtime = x.split('<div class="duration">')
				gtime = gtime[1].split('</div>');
				timp = gtime[0]
				if len(timp) == 4:
					timp = '0' + timp
				gobject.idle_add(pymaxe.addToList, [video, title, timp, url])
			except Exception, e:
				print e
#				import traceback
#				traceback.print_exc()

	def searchImage(self, string, pymaxe):
		image = gtk.gdk.pixbuf_new_from_file(__path__[0] + '/trilulilu_image.png')
		req = urllib2.Request('http://cauta.trilulilu.ro/imagini/' + urllib.quote(string));
		getdata = self.opener.open(req);
		data = getdata.read();
		results = data.split('<div class="item_details">');
		results.pop(0)
		for x in results:
			try:
				import time
				gurl = x.split('<span class="title"><a href="')
				gurl = gurl[1].split('">')
				url = gurl[0]
				gtitle = gurl[1].split('</a></span>')
				gtitle = gtitle[0]
				title = gtitle.replace('&#039;', "'")
				if '&amp;amp;' in title:
					title = title.replace('&amp;', '&')
				title = title.replace('&amp;', '&')
				title = '<b>' + gobject.markup_escape_text(title) + '</b>'
				timp = ''
				if len(timp) == 4:
					timp = '0' + timp
				gobject.idle_add(pymaxe.addToList, [image, title, timp, url])
			except Exception, e:
				print e
#				import traceback
#				traceback.print_exc()
	
	def getDetails(self, pymaxe, url):
		initLang()
		try:
			data = self.fileData(url)
			if data == False:
				pymaxe.isWorking = False
				gobject.idle_add(self.showDialog, gtk.MESSAGE_ERROR, _('Error'), _('Couldn\'t read data. Possible reasons:\n\n* You gave us an invalid URL\n* There\'s a problem with your internet connection\n* Cannot establish a connection with Trilulilu\n* Crocodilu\' encountered an techincal problem\n* Crocodilu\' changed something in page layout and fucked up all the things\n\nThere\'s no workaround yet, sorry'))
				gobject.idle_add(pymaxe.restoreState)
				return			
			gui = gtk.Builder()
			gui.add_from_file(__path__[0] + '/trilulilu.glade')
			vbox = gui.get_object('vbox1')
			gui.get_object('label1').set_markup('<i>' + data['descriere'] + '</i>')
			gui.get_object('radiobutton1').set_active(True)
			tip = data['format']
			if tip != 'audio':
				img = gui.get_object('image1')
				img.show()
				Thread(target=self.TRpreview, args=(url, img)).start()
			else:
				gui.get_object('image1').hide()
			pymaxe.doConvert = False
			gui.get_object('checkbutton5').set_active(self.str2bool(pymaxe.getSetting('General', 'noconvert')))
			if tip == 'audio':
				gui.get_object('radiobutton3').set_sensitive(False)
				gui.get_object('radiobutton2').set_sensitive(False)
				gui.get_object('checkbutton5').set_sensitive(False)
				data['tip'] = '.mp3'
				data['format'] = 'MPEG I Layer 3'
			elif tip == 'video':
				gui.get_object('radiobutton1').connect("toggled", self.changeOption, pymaxe, gui)
				gui.get_object('radiobutton3').connect("toggled", self.changeOption, pymaxe, gui)
				gui.get_object('radiobutton2').connect("toggled", self.changeOption, pymaxe, gui)
				gui.get_object('checkbutton5').connect("toggled", self.changeOption, pymaxe, gui)
				gui.get_object('radiobutton3').set_sensitive(False)
				pymaxe.doConvert = 'audio'
				data['tip'] = '.mp3'
				data['format'] = 'Video'
			elif tip == 'image':
				gui.get_object('radiobutton1').set_sensitive(False)
				gui.get_object('radiobutton2').set_sensitive(False)
				gui.get_object('checkbutton5').set_sensitive(False)
				gui.get_object('radiobutton3').set_active(True)
				data['format'] = 'JPEG'
				data['tip'] = '.jpg'
			gobject.idle_add(pymaxe.showDetails, data, vbox)
		except Exception, e:
			pymaxe.isWorking = False
			gobject.idle_add(self.showDialog, gtk.MESSAGE_ERROR, _('Error'), _('Couldn\'t read data. Possible reasons:\n\n* You gave us an invalid URL\n* There\'s a problem with your internet connection\n* Cannot establish a connection with Trilulilu\n* Crocodilu\' encountered an techincal problem\n* Crocodilu\' changed something in page layout and fucked up all the things\n\nThere\'s no workaround yet, sorry'))
			gobject.idle_add(pymaxe.restoreState)
			return False		
		#pymaxe.showDetails(url, titlu, durata, downurl, tip)

	def fileData(self, url):
		print url
		req = urllib2.Request(url);
		getdata = self.opener.open(req);
		data = getdata.read();
		if data.find('Acest utilizator si-a dezactivat contul') != -1:
			return False
#		if data.find('http://static.trilulilu.ro/flash/audioplayer2010.swf') != -1:
#			tip = 'audio'
#			v = 3
#		elif data.find('http://static.trilulilu.ro/flash/videoplayer2010.swf') != -1:
#			tip = 'video'
#			v = 3
#		elif data.find('img_player') != -1:
#			v = 3
#			tip = 'image'
		if data.find('http://embed.trilulilu.ro/audio') != -1:
			tip = 'audio'
		elif data.find('http://embed.trilulilu.ro/video') != -1:
			tip = 'video'
		elif data.find('http://embed.trilulilu.ro/image') != -1:
			tip = 'image'
			
		try:
#			if v == 3:
				print 'Trilulilu V3'
				if tip != 'image':
					gflashvars = data.split('flashvars="userid=')
					gflashvars = gflashvars[1].split('"')
					flashvars = gflashvars[0]
					gserver = flashvars.split('&server=');
					gserver = gserver[1].split('&');
					server = gserver[0];
					ghash = flashvars.split('&hash=');
					ghash = ghash[1].split('&');
					shash = ghash[0]
					gusername = data.split('flashvars="userid=')[1].split('&');
					username = gusername[0];
					gkey = data.split('&key=');
					gkey = gkey[1].split('"')
					key = gkey[0]
					if key == '':
						key = 'ministhebest'			# WTF?
					gtitlu = data.split('<title>')
					gtitlu = gtitlu[1].split('</title>')
					titlu = gtitlu[0].replace('&amp;', '&')
					titles = titlu.split(' - ')
					titles.pop(len(titles)-1)
					titlu = ' - '.join(titles)
					titlu = titlu.replace('&#039;', "'")
					titlu = titlu.replace('Trilulilu - ', '')
					if '&amp;' in titlu:
						titlu = titlu.replace('&amp;', '&')
					try:
						gdescriere = data.split('<span class="links">')
						descriere = gdescriere[1].split('</span>')
						descriere =  h.unescape(descriere[0])
						descriere = descriere.replace('&', '&amp;')
					except:
						descriere = ''
					downurl = "http://fs" + server + ".trilulilu.ro/stream.php?type="+tip+"&source=site&hash=" + shash + "&username=" + username + "&key=" + key
					durata = 'N/A'
					data = {"url" : url,
						"titlu" : titlu,
						"durata" : durata,
						"tip" : '.mp3',
						"format" : tip,
						"downurl" : downurl,
						"descriere" : descriere}
					return data
				else:
					imgdata = data.split('<div class="img_player">')
					imgdata = imgdata[1].split('</div>')
					imgdata = imgdata[0]
					imgsrc = imgdata.split('<img src="')
					imgsrc = imgsrc[1].split('"')
					imgsrc = imgsrc[0]
					gtitle = data.split('<title>')
					gtitle = gtitle[1].split('</title>')
					titlu = gtitle[0]
					titles = titlu.split(' - ')
					titles.pop(len(titles)-1)
					titlu = ' - '.join(titles)
					titlu = titlu.replace('Trilulilu - ', '')
					durata = 'N/A'
					format = tip
					gdescriere = data.split('<span class="links">')
					descriere = gdescriere[1].split('</span>')
					descriere =  h.unescape(descriere[0])
					descriere = descriere.replace('&', '&amp;')
					data = {"url" : url,
						"titlu" : titlu,
						"durata" : durata,
						"tip" : '.mp3',
						"format" : tip,
						"downurl" : imgsrc,
						"descriere" : descriere}
					return data
#			elif v == 2:
#				print 'Trilulilu V2'
#				gserver = data.split('so.addVariable("server", "');
#				gserver = gserver[1].split('")');
#				server = gserver[0];
#				ghash = data.split('so.addVariable("hash", "');
#				ghash = ghash[1].split('")');
#				shash = ghash[0]
#				gusername = data.split('so.addVariable("userid", "');
#				gusername = gusername[1].split('")');
#				username = gusername[0];
#				gkey = data.split('so.addVariable("key", "');
#				gkey = gkey[1].split('")')
#				key = gkey[0]
#				gtitlu = data.split('<meta name="title" content="')
#				gtitlu = gtitlu[1].split('" />')
#				titlu = gtitlu[0].replace('&amp;', '&')
#				titlu = titlu.replace('&#039;', "'")
#				if '&amp;' in titlu:
#					titlu = titlu.replace('&amp;', '&')
#				gdescriere = data.split('"description":"')
#				descriere = gdescriere[1].split('","')
#				descriere =  h.unescape(descriere[0])
#				descriere = descriere.replace('&', '&amp;')
#				downurl = "http://fs" + server + ".trilulilu.ro/stream.php?type="+tip+"&source=site&hash=" + shash + "&username=" + username + "&key=" + key
#				durata = 'N/A'
#				data = {"url" : url,
#					"titlu" : titlu,
#					"durata" : durata,
#					"tip" : '.mp3',
#					"format" : tip,
#					"downurl" : downurl,
#					"descriere" : descriere}
#				return data
		except Exception, e:
#			import traceback
#			traceback.print_exc()
			print e
			return False
	
	def changeOption(self, obj, pymaxe, gui):
		currentName = pymaxe.gui.get_object('entry2').get_text()
		currentName = os.path.splitext(currentName)[0]
		if gui.get_object('radiobutton1').get_active():
			gui.get_object('checkbutton5').set_sensitive(False)
			pymaxe.gui.get_object('entry2').set_text(currentName + '.mp3')
			pymaxe.doConvert = 'audio'
		if gui.get_object('radiobutton2').get_active():
			gui.get_object('checkbutton5').set_sensitive(True)
			if gui.get_object('checkbutton5').get_active():
				pymaxe.doConvert = False
				pymaxe.gui.get_object('entry2').set_text(currentName + '.flv')
			else:
				pymaxe.doConvert = 'video'
				pymaxe.gui.get_object('entry2').set_text(currentName + '.avi')
		if gui.get_object('radiobutton3').get_active():
			pymaxe.gui.get_object('entry2').set_text(currentName + '.jpg')
			pymaxe.doConvert = False

	def showDialog(self, type, title, message):
			gtk.gdk.threads_enter()
			dialog = gtk.MessageDialog(parent=None, flags=0, type=gtk.MESSAGE_ERROR, buttons=gtk.BUTTONS_CLOSE, message_format=message);
			dialog.set_title(title);
			dialog.run();
			dialog.destroy();
			gtk.gdk.threads_leave()
	
	def config(self, pymaxe):
		initLang()
		gui = gtk.Builder()
		gui.add_from_file(__path__[0] + '/trilulilucfg.glade')
		gui.connect_signals({"changeSearch" : (self.changeSearch, pymaxe), "close" : (self.close, gui)})
		gui.get_object('window1').set_title('Configurare Trilulilu')
		gui.get_object('checkbutton1').props.name = 'checkbutton1'
		gui.get_object('checkbutton2').props.name = 'checkbutton2'
		gui.get_object('checkbutton3').props.name = 'checkbutton3'
		if pymaxe.getSetting('Plugins', 'TriluliluMusic') == 'False':
			gui.get_object('checkbutton1').set_active(False)
		if pymaxe.getSetting('Plugins', 'TriluliluVideo') == 'False':
			gui.get_object('checkbutton2').set_active(False)
		if pymaxe.getSetting('Plugins', 'TriluliluImage') == 'False':
			gui.get_object('checkbutton3').set_active(False)
		gui.get_object('window1').show()

	def changeSearch(self, obj, pymaxe):
		if obj.name == 'checkbutton1':
			if obj.get_active():
				pymaxe.setSetting('Plugins', 'TriluliluMusic', 'True')
			else:
				pymaxe.setSetting('Plugins', 'TriluliluMusic', 'False')
		if obj.name == 'checkbutton2':
			if obj.get_active():
				pymaxe.setSetting('Plugins', 'TriluliluVideo', 'True')
			else:
				pymaxe.setSetting('Plugins', 'TriluliluVideo', 'False')
		if obj.name == 'checkbutton3':
			if obj.get_active():
				pymaxe.setSetting('Plugins', 'TriluliluImage', 'True')
			else:
				pymaxe.setSetting('Plugins', 'TriluliluImage', 'False')

	def str2bool(self, v):
		return v.lower() in ["yes", "true", "t", "1"]	

	def TRpreview(self, url, img):
		gurl = url.split('trilulilu.ro/')
		url = gurl[1]
		req = urllib2.Request('http://thumbs13.trilulilu.ro/'+url+'/thumb');
		getdata = self.opener.open(req);
		data = getdata.read();
		pbl = gtk.gdk.PixbufLoader()
		pbl.write(data)
		pbl.close()
		gobject.idle_add(img.set_from_pixbuf, pbl.get_pixbuf())

	def close(self, obj, gui):
		gui.get_object('window1').destroy()
		
	def stopSearch(self, obj, pymaxe):
		pymaxe.isWorking = False
		if hasattr(self, 'tmusic'):
			if self.tmusic.is_alive():
				self.tmusic.terminate()
		if hasattr(self, 'tvideo'):
			if self.tvideo.is_alive():
				self.tvideo.terminate()
		if hasattr(self, 'timage'):
			if self.timage.is_alive():
				self.timage.terminate()

	def quit(self):
		exit()

	def uninstall(self, pymaxe):
		pymaxe.triluliluMenu.destroy()
		del pymaxe.triluliluMenu
		try:
			pymaxe.gui.get_object('button19').disconnect(self.stopSearchConn)
		except:
			pass
